package org.jhub1.system.xmpp.proxy;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;

import org.jhub1.system.xmpp.gateway.packet.SubItemable;
import org.jhub1.system.xmpp.log.LogAdapter;

public class HTTPGatewayRequest {

	private static LogAdapter log = LogAdapter.getLog(HTTPGatewayRequest.class);
	private String host;
	private int port;

	public HTTPGatewayRequest(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public ProcessResponse getResult(String method, String uri,
			Iterator<SubItemable> params) {
		ProcessResponse pr = null;
		if (method.equals("GET")) {
			pr = doGETJson(uri, params);
		} else {
			pr = doPOSTJson(uri, params);
		}
		return pr;
	}

	public ProcessResponse doPOSTJson(String uri, Iterator<SubItemable> params) {
		HttpURLConnection connection = null;
		PrintWriter outWriter = null;
		BufferedReader serverResponse = null;
		StringBuffer buff = new StringBuffer();
		StringBuilder output = new StringBuilder();
		ProcessResponse pr = new ProcessResponse();
		try {
			// OPEN CONNECTION
			connection = (HttpURLConnection) new URL("http", this.host,
					this.port, uri).openConnection();

			// SET REQUEST INFO
			// for some reasons it always do post!!!!
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setAllowUserInteraction(false);
			connection.addRequestProperty("Accept", "application/json");
			// connection.setReadTimeout(10000);

			// CREATE A WRITER FOR OUTPUT
			outWriter = new PrintWriter(connection.getOutputStream());

			// PARAMETERS
			if (params != null) {
				// buff.append("param1=");
				// buff.append(URLEncoder.encode("Param 1 Value", "UTF-8"));
				// buff.append("&");
				// buff.append("param2=");
				// buff.append(URLEncoder.encode("Param 2 Value", "UTF-8"));
			}

			// SEND PARAMETERS
			outWriter.println(buff.toString());
			outWriter.flush();
			outWriter.close();

			// RESPONSE STREAM
			serverResponse = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));

			// READ THE RESPOSNE
			String line;
			while ((line = serverResponse.readLine()) != null) {
				output.append(line);
			}
			pr.resultMessage = output.toString();
		} catch (MalformedURLException mue) {
			log.error(mue.toString());
			pr.setError("Malformed_URL_Exception");
		} catch (IOException ioe) {
			log.error(ioe.toString());
			pr.setError("IO_Exception");
		} finally {
			if (connection != null)
				connection.disconnect();

			if (serverResponse != null) {
				try {
					serverResponse.close();
				} catch (Exception ex) {
					log.error(ex.toString());
				}
			}
		}
		return pr;
	}

	public ProcessResponse doGETJson(String uri, Iterator<SubItemable> params) {
		StringBuilder sbquery = new StringBuilder();
		ProcessResponse pr = new ProcessResponse();
		String uriString;

		if (params != null) {
			sbquery.append("?");
			while (params.hasNext()) {
				SubItemable sub = (SubItemable) params.next();
				sbquery.append(sub.getName()).append("=")
						.append(sub.getValue());
				if (params.hasNext()) {
					sbquery.append("&");
				}
			}
		}
		if (sbquery.length() > 0) {
			uriString = uri + "/" + sbquery.toString();
		} else {
			uriString = uri;
		}
		try {
			URL url = new URL("http", this.host, this.port, uriString);
			URLConnection conn = url.openConnection();
		//	System.out.println(url.toString());
			// Get the response
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					conn.getInputStream()));
			StringBuffer sb = new StringBuffer();
			String line;
			while ((line = rd.readLine()) != null) {
				sb.append(line);
			}
			rd.close();
			pr.resultMessage = sb.toString();
		} catch (Exception e) {
			log.error(e.toString());
			pr.setError(e.toString());
			//e.printStackTrace();
		}
		return pr;
	}

}
